package com.example.newspublish.util;


import com.example.newspublish.pojo.entity.User;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.function.Function;


/**
 * JWT token manager

 */
@Slf4j
@Component
public class JwtTokenManager {

    // 密钥，请根据实际情况更改
    private final String SECRET_KEY = "Viper";

    // 生成token
    public String generateToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", user.getUsername());
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(user.getUsername())
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 设置token有效期，这里设置为24小时
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    //从jwt获取用户名
    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    //从jwt获取日期
    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    //解析jwt令牌
    private Claims extractAllClaims(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
    }

    public Boolean validateToken(String token) {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Authentication authentication = getAuthentication(token);
        System.out.println("请求认证信息:"+authentication);
        String authenticationUsername = authentication.getName();
        String username = extractUsername(token);
        System.out.println("authenticationUsername:"+authenticationUsername+",username"+username);
        return (username.equals(authenticationUsername) && !isTokenExpired(token));
    }

    private Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    //解析jwt令牌
    private Object parse(String token) {
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws = jwtParser.setSigningKey(SECRET_KEY).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        System.out.println(claims.get("username"));

        return claims.get("username");
    }

    public Authentication getAuthentication(String token) {
        return new UsernamePasswordAuthenticationToken( extractUsername(token), null, null);
    }

}
